/**
 * 
 */
package com.desksoft.ecommerce.util.holder;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/***************************************
 * <pre>
 * 版权所有：杭州迪科软件 保留所有权利
 * 创建日期: Jun 28, 2011 4:49:34 PM
 * 创建作者：yejw
 * 文件名称：ApplicationContextHolder.java
 * 版本：
 * 功能：
 * 最后修改时间：Jun 28, 2011 4:49:34 PM
 * 修改记录：
 * </pre>
 *****************************************/

public class ApplicationContextHolder implements ApplicationContextAware {

	private static Log log = LogFactory.getLog(ApplicationContextHolder.class);

	private static ApplicationContext applicationContext;

	/**
	 * 获取容器
	 * 
	 * @return
	 */
	public static ApplicationContext getApplicationContext() {
		if (applicationContext == null) {
			throw new IllegalStateException( "'applicationContext' property is null,ApplicationContextHolder not yet init.");
		}
		
		return applicationContext;
	}

	/**
	 * 获取BEAN
	 * 
	 * @param beanName
	 * @return
	 */
	public static Object getBean(String beanName) {
		return getApplicationContext().getBean(beanName);
	}
	
	/**
	 * 获取BEAN
	 * 
	 * @param <T>
	 * @param beanName
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static <T> T get(final String beanName) {
		return (T) getBean(beanName);
	}

	/**
	 * 清除容器引用
	 */
	public static void cleanHolder() {
		applicationContext = null;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.springframework.context.ApplicationContextAware#setApplicationContext
	 * (org.springframework.context.ApplicationContext)
	 */
	@SuppressWarnings("static-access")
	@Override
	public void setApplicationContext(ApplicationContext context)
			throws BeansException {
		if (this.applicationContext != null) {
			throw new IllegalStateException( "ApplicationContextHolder already holded 'applicationContext'.");
		}
		
		this.applicationContext = context;
		
		log.info("holded applicationContext, displayName:" + applicationContext.getDisplayName());
	}
	
}